#!/usr/local/bin/python
# Checks lengths of proteins from BLAST hits and prints if our protein has
# same length as lengths of other proteins. Reports length as average percentage
# of query/hit length.
# Usage: python check_blast_lengths.py blastfile.something.tbl

import sys, re

filename = sys.argv[1]

locus_tag = filename.split('.')

name = locus_tag[0] + "." + locus_tag[1] + "."+ locus_tag[2]

f = open(filename, "rU")

def fmt(f):
    st = '{0:.6}'.format(f)
    return st

lines = f.readlines()

m1 = re.compile('(.*\[.*\].*)\[(.*)\]')

m2 = re.compile('(.*)\[(.*)\]')

m3 = re.compile('(.*)\[(.*)')

lengths = []

if len(lines) == 0:
    #print sys.argv[1], "\t", "-"
    pass
else:
    st = lines[0]
    line = st.split('\t')
    evalue = line[1]
    percent_id = line[3]
    percent_sim = line[4]
    qlength = float(line[6])
    qstart = float(line[7])
    qstop = float(line[8])
    acc = line[9]
    hlength = float(line[10])
    hstart = float(line[11])
    hstop = float(line[12])
    hdef = line[13]
    if m1.match(hdef):
        pattern = m1.match(hdef)
        definition = pattern.group(1)
        organism = pattern.group(2)
    elif m2.match(hdef):
        pattern = m2.match(hdef)
        definition = pattern.group(1)
        organism = pattern.group(2)
    else:
        pattern = m3.match(hdef)
        definition = pattern.group(1)
        organism = pattern.group(2)

    m = re.split('\|', acc)
    #match_length = ((qstop - qstart + 1) / (hstop - hstart + 1)) * 100
    match_length = (qlength / hlength) * 100
    lengths.append(match_length)

mls = len(lengths)

totalsum = 0

for i in lengths:
    totalsum += i

if mls > 0:
    print locus_tag[0] + "\t" + fmt(str(totalsum / mls))
else:
    print locus_tag[0] + "\t" + "No BLAST hit"

f.close()

